<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="query">
                <el-form-item>
                    <el-input v-model="query.keyword" placeholder="关键字"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="search">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="this.pageInfo.rows" highlight-current-row v-loading="listLoading"
                  @selection-change="selsChange"
                  style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="name" label="角色名字" width="120" sortable>
            </el-table-column>
            <el-table-column prop="sn" label="sn" width="200" sortable>
            </el-table-column>

            <el-table-column label="操作" width="400">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                    <el-button type="warning" size="small" @click="handlePermission(scope.$index, scope.row)">设置权限</el-button>
                    <el-button type="warning" size="small" @click="handlePermission(scope.$index, scope.row)">设置菜单</el-button>




                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" :current-page="query.currentPage"
                           @current-change="handleCurrentChange" :page-size="this.query.pageSize"
                           :total="this.pageInfo.total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--新增编辑页面-->
        <el-dialog title="编辑/新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
            <el-form :model="saveForm" label-width="80px" ref="saveForm">
                <el-form-item label="角色名称">
                    <el-input v-model="saveForm.name" auto-complete="off"></el-input>
                </el-form-item>

                <el-form-item label="标识">
                    <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click.native="saveFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
            </div>
        </el-dialog>

        <el-dialog title="设置权限" :visible.sync="setPermissionVisible" :close-on-click-modal="false">

            <el-form :model="rolePermission" label-width="80px" ref="saveForm">
                <!--indeterminate属性用于实现全选效果-->
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
                </el-checkbox>
                <div class="checkbox-table" v-for="(p,indexkey) in permissionTree" :key="p.sn">
                    <template>
                        <!--一级复选框-->
                        <el-checkbox class="check1" style="font-weight: 600;margin-bottom: 15px "
                                     v-model='rolePermission.permissionSns' :label="p.sn"
                                     @change='handleCheck(1,indexkey)'>
                            {{ p.name }}
                        </el-checkbox>
                        <div style="margin-bottom: 20px;">
                            <!--二级复选框-->
                            <div v-for="c in p.children" class="line-check" :key="c.sn"
                                 style="display: inline-block; margin-left: 20px;margin-bottom: 20px;">
                                <el-checkbox class="check2" @change='handleCheck(2,indexkey)'
                                             v-model="rolePermission.permissionSns" :label="c.sn">
                                    {{ c.name }}
                                </el-checkbox>
                            </div>
                        </div>
                    </template>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="setPermissionVisible = false">取消</el-button>
                <el-button type="primary" @click.native="saveRolePermission" :loading="saveLoading">提交</el-button>
            </div>
        </el-dialog>




    </section>
</template>

<script>


export default {
    data() {
        return {

            saveLoading: false,

            saveForm: {
                id: null,
                name: '',
                sn: ''
            },
            saveFormVisible: false,
            setPermissionVisible: false,
            rolePermission: {
                roleId:null,
                permissionSns: []
            },
            permissionTree: [], //存放权限树，用来做弹框的权限树展示
            isIndeterminate: false, //用来控制全选矿的状态
            checkAll: false, //控制全选框是否选中

            listLoading: false,
            sels: [],//列表选中列


            query: {
                keyword: "",
                currentPage: 1,
                pageSize: 5
            },

            pageInfo: {
                total: 0,
                rows: []
            },
            allPermissionSns: [] //用来装所有权限的sn
        }
    },
    methods: {
        saveRolePermission(){
            this.$http.post("/role/permission",this.rolePermission)
                .then(result => {
                    result = result.data;
                    if (result.success){
                        this.$message({
                            message: '保存成功',
                            type: 'success'
                        });
                        this.setPermissionVisible = false
                    }
                }).catch(result => {
                this.$message({
                    message: '网络错误',
                    type: 'error'
                });
            })
        },
        handleCheckAllChange(val) {
            this.rolePermission.permissionSns = val ? this.allPermissionSns : [];
            this.isIndeterminate = false;
        },
        // 处理选择事件  type 1:一级权限2:二级权限   a：一级权限的索引位置
        handleCheck(type, a = 0) { // 多选框
            // 在已选中的权限列表中，查看是否存在一级权限 >-1 存在  <0 不存在
            let indexOf = this.rolePermission.permissionSns.indexOf(this.permissionTree[a].sn);
            if (type == 2) { // 二级菜单点击
                let index = 0;  //
                this.permissionTree[a].children.map(item => {
                    // 已选中的权限列表中，是否包含当前一级权限下的某个子权限
                    if (this.rolePermission.permissionSns.indexOf(item.sn) > -1) {
                        index += 1;
                    }
                })
                if (index > 0) {  // 已选中的权限列表中，包含当前一级权限下的某个子权限
                    if (indexOf < 0) {  // 已选中的权限列表中，没有当前一级权限，则添加到已选中的权限列表中
                        this.rolePermission.permissionSns.push(this.permissionTree[a].sn);
                    }
                } else {  // // 已选中的权限列表中，不包含当前一级权限下的某个子权限
                    if (indexOf > -1) {// 已选中的权限列表中，有当前一级权限，则删除
                        this.rolePermission.permissionSns.splice(indexOf, 1);
                    }
                }
            } else {  // 一级菜单点击
                if (indexOf > -1) { // 已选中的权限中，包含当前一级权限，则将该一级权限下所有的子权限选中
                    this.permissionTree[a].children.map(item => {
                        if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) < 0) {
                            this.rolePermission.permissionSns.push(item.sn)
                        }
                    })
                } else {
                    // 已选中的权限中，不包含当前一级权限，则将该一级权限下所有的子权限移除
                    this.permissionTree[a].children.map(item => {
                        if (this.rolePermission.permissionSns.findIndex((n) => n == item.sn) > -1) {
                            this.rolePermission.permissionSns.splice(this.rolePermission.permissionSns.findIndex((n) => n == item.sn), 1);
                        }
                    })
                }
            }
            // 获取已选中的长度
            let checkedCount = this.rolePermission.permissionSns.length;
            // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
            this.checkAll = checkedCount === this.allPermissionSns.length;
            // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
        },
        handleRole(index, row) {

        },
        handlePermission(index, row) {
            this.setPermissionVisible = true;
            this.getPermissionTree();
            //获取所有的权限sn
            this.getAllPermissionSn();
            this.rolePermission.roleId = row.id;

            //通过id查询当前角色拥有的权限
            this.getPermissionByRoleId(row.id);
        },
        getPermissionByRoleId(roleId) {
            this.$http.get("/role/permission/"+roleId)
                .then(result => {
                    result = result.data;
                    this.rolePermission.permissionSns = result.data;
                    // 获取已选中的长度
                    console.log("------",result.data)
                    let checkedCount = this.rolePermission.permissionSns.length;
                    // 如果已选中的长度==所有权限的长度，则checkAll=true，也就是全选框被选中
                    this.checkAll = checkedCount === this.allPermissionSns.length;
                    // 如果已选中的长度>0并且已选中的长度<所有权限的长度，则全选框是一个横杠
                    this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPermissionSns.length;
                })
        },
        getAllPermissionSn() {
            this.$http.get("/permission/sns")
                .then(result => {
                    result = result.data;
                    this.allPermissionSns = result.data;
                })
        },
        getPermissionTree() {
            this.$http.get("/permission/tree")
                .then(result => {
                    result = result.data;
                    this.permissionTree = result.data
                }).catch(result => {
                this.$message({
                    message: '网络错误',
                    type: 'error'
                });
            })
        },
        handleAdd() {
            this.saveFormVisible = true;
            //每次新增都要将表单数据初始化
            this.saveForm = {
                id: null,
                name: '',
                sn: ''
            };

        },

        handleEdit(index, row) {
            this.saveFormVisible = true;

            this.saveForm = Object.assign({}, row);

        },
        saveSubmit() {
            this.$confirm('要确定提交吗？', '提示', {}).then(() => {
                this.addLoading = true;

                this.$http.put("/role", this.saveForm)
                    .then(result => {
                        result = result.data;
                        if (result.success) {
                            this.$message({
                                message: '成功',
                                type: 'success'
                            });
                        }
                        this.saveFormVisible = false;
                        this.getRole();
                    })
                    .catch(result => {
                        this.$message({
                            message: '网络错误',
                            type: 'error'
                        });
                    });
            })
        },
        search() {
            this.query.currentPage = 1;
            this.getRole();
        },

        handleCurrentChange(val) {
            this.query.currentPage = val;
            this.getRole();
        },

        getRole() {
            this.$http.post("/role", this.query)
                .then(result => {
                    result = result.data;
                    this.pageInfo = result.data
                })
        },
        //删除
        handleDel: function (index, row) {
            this.$confirm('确认删除该记录吗?', '提示', {
                type: 'warning'
            }).then(() => {//确认删除的按钮
                //加载页面设为true
                this.listLoading = true;
                //获取删除数据id
                let id = row.id;
                this.$http.delete("/role/" + id)
                    .then(result => {
                        //关闭加载框
                        this.listLoading = false;
                        //重新查询数据
                        this.search()
                        result = result.data
                        if (result.success) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
                        }
                    })
            })
        },

        selsChange: function (sels) {
            this.sels = sels;
        },
        //批量删除
        batchRemove: function () {
            var ids = this.sels.map(item => item.id);
            this.$confirm('确认删除选中记录吗？', '提示', {
                type: 'warning'
            }).then(() => {
                this.listLoading = true;

                this.$http.patch("/role/", ids)
                    .then(result => {
                        //关闭加载框
                        this.listLoading = false;
                        //重新查询数据
                        this.search()
                        result = result.data
                        if (result.success) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: '删除失败',
                                type: 'error'
                            });
                        }
                    })

            }).catch(() => {

            });
        }


    },
    mounted() {
        this.getRole();
    }
}

</script>

<style scoped>

</style>